import React, { Component } from 'react'
import './index.css'

export default class Item extends Component {
  // 鼠标是否进入该Item
  state = { mouse: false }
  // 鼠标移出进入的回调
  handleMouse = (flag) => {
    // 必须返回一个函数
    return () => {
      this.setState({ mouse: flag })
    }
  }
  // 复选框变化的回调
  handleCheck = (id) => {
    return (event) => {
      console.log(id, event.target.checked);
      this.props.updateTodo(id, event.target.checked)
    }
  }
  // 删除一项
  deleteTodo = (id) => {
    if (window.confirm('确定删除吗？')) {
      this.props.deleteTodo(id)
    }
  }
  render() {
    const { id, name, done } = this.props
    const { mouse } = this.state
    return (
      <li style={{ backgroundColor: mouse ? '#ccc' : '' }} onMouseEnter={this.handleMouse(true)} onMouseLeave={this.handleMouse(false)}>
        <label>
          <input type="checkbox" checked={done} onChange={this.handleCheck(id)} />
          <span>{name}</span>
        </label>
        <button onClick={() => { this.deleteTodo(id) }} className="btn btn-danger" style={{ display: mouse ? 'block' : 'none' }}>
          删除
        </button>
      </li>
    )
  }
}
